package com.fourfaith.iot.beidou.utils;

/**
 * @Name Byte2HexUtil
 * @Description ${}
 * @Author shiyunan
 * @Create 2022/2/26 11:59
 */
public class Byte2HexUtil {

    private static final String HEX_STRING = "0123456789ABCDEF";
    /**
     * convert byte[] to HexString
     *
     * @param bArray
     * @return
     */
    public static String bytesToHexString(byte[] bArray) {
        int length = bArray.length;
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2) {
                sb.append(0);
            }
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * convert HexString to byte[]
     *
     * @param hex
     * @return
     */
    public static byte[] hexStringToByte(String hex) {
        int len = (hex.length() / 2);
        byte[] result = new byte[len];
        char[] achar = hex.toCharArray();

        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
        }
        return result;

    }

    public static byte toByte(char c) {
        return (byte) HEX_STRING.indexOf(c);
    }
}
